<template>
  <div class="announcement-page">
    <div class="page-header">
      <button class="back-button" @click="goToHome">
        <span class="icon-arrow-left"></span>
        返回首页
      </button>
      <h1>公告管理</h1>
    </div>
    
    <div class="page-content">
      <div class="config-header">
        <p>发布和管理系统公告，向用户传达重要信息和更新</p>
        <button class="primary-btn" @click="showAddAnnouncementModal = true">
          <i class="icon-plus"></i> 发布公告
        </button>
      </div>
      
      <div class="card">
        <div class="filter-bar">
          <select v-model="selectedStatus" class="filter-select" @change="filterAnnouncements">
            <option value="">全部状态</option>
            <option value="published">已发布</option>
            <option value="draft">草稿</option>
            <option value="expired">已过期</option>
          </select>
          
          <input 
            type="text" 
            v-model="searchKeyword" 
            placeholder="搜索公告标题..."
            class="search-input"
            @keyup.enter="filterAnnouncements"
          >
          <button class="search-btn" @click="filterAnnouncements">搜索</button>
        </div>
        
        <div class="announcements-list">
          <div class="announcement-item" v-for="announcement in filteredAnnouncements" :key="announcement.id">
            <div class="announcement-header">
              <div class="announcement-status">
                <span :class="'status-tag status-' + announcement.status">
                  {{ announcement.status === 'published' ? '已发布' : announcement.status === 'draft' ? '草稿' : '已过期' }}
                </span>
                <span v-if="announcement.isTop" class="top-tag">置顶</span>
              </div>
              <div class="announcement-date">
                {{ announcement.status === 'published' ? '发布于 ' + formatDate(announcement.publishTime) : 
                   announcement.status === 'expired' ? '过期于 ' + formatDate(announcement.expireTime) : 
                   '创建于 ' + formatDate(announcement.createTime) }}
              </div>
            </div>
            
            <div class="announcement-body">
              <h3 class="announcement-title">{{ announcement.title }}</h3>
              <div class="announcement-content">
                {{ announcement.content.length > 150 ? announcement.content.substring(0, 150) + '...' : announcement.content }}
              </div>
              
              <div class="announcement-meta" v-if="announcement.status === 'published'">
                <span class="meta-item">
                  <i class="icon-view"></i> {{ announcement.viewCount }} 次查看
                </span>
                <span class="meta-item" v-if="announcement.expireTime">
                  <i class="icon-expire"></i> 有效期至: {{ formatDate(announcement.expireTime) }}
                </span>
              </div>
            </div>
            
            <div class="announcement-footer">
              <button class="edit-btn" @click="editAnnouncement(announcement)">编辑</button>
              <button class="delete-btn" @click="deleteAnnouncement(announcement.id)">删除</button>
              
              <template v-if="announcement.status === 'draft'">
                <button class="publish-btn" @click="publishAnnouncement(announcement.id)">发布</button>
              </template>
              
              <template v-if="announcement.status === 'published'">
                <button class="top-btn" @click="toggleTop(announcement.id)">
                  {{ announcement.isTop ? '取消置顶' : '置顶' }}
                </button>
                <button class="expire-btn" @click="expireAnnouncement(announcement.id)">
                  设为过期
                </button>
              </template>
            </div>
          </div>
          
          <div class="empty-state" v-if="filteredAnnouncements.length === 0">
            <i class="icon-empty"></i>
            <p>暂无公告，请点击发布公告按钮创建</p>
          </div>
        </div>
      </div>
    </div>
    
    <!-- 新增/编辑公告模态框 -->
    <div class="modal-overlay" v-if="showAddAnnouncementModal || showEditAnnouncementModal">
      <div class="modal">
        <div class="modal-header">
          <h3>{{ showEditAnnouncementModal ? '编辑公告' : '发布公告' }}</h3>
          <button class="close-btn" @click="closeAnnouncementModal">&times;</button>
        </div>
        <div class="modal-body">
          <form class="announcement-form">
            <div class="form-group">
              <label>公告标题 *</label>
              <input 
                type="text" 
                v-model="currentAnnouncement.title" 
                class="form-control"
                required
              >
            </div>
            
            <div class="form-group">
              <label>公告内容 *</label>
              <textarea 
                v-model="currentAnnouncement.content" 
                class="form-control announcement-content"
                rows="8"
                required
              ></textarea>
            </div>
            
            <div class="form-group">
              <label>有效期至</label>
              <input 
                type="datetime-local" 
                v-model="currentAnnouncement.expireTime" 
                class="form-control"
              >
              <p class="form-hint">不设置则永久有效</p>
            </div>
            
            <div class="form-group" v-if="showEditAnnouncementModal && currentAnnouncement.status === 'published'">
              <label class="checkbox-label">
                <input 
                  type="checkbox" 
                  v-model="currentAnnouncement.isTop"
                >
                置顶公告
              </label>
            </div>
            
            <div class="form-actions" v-if="showEditAnnouncementModal && currentAnnouncement.status === 'draft'">
              <button 
                type="button" 
                class="publish-btn modal-publish-btn"
                @click="saveAndPublish"
              >
                保存并发布
              </button>
            </div>
          </form>
        </div>
        <div class="modal-footer">
          <button class="cancel-btn" @click="closeAnnouncementModal">取消</button>
          <button 
            class="primary-btn" 
            @click="saveAnnouncement"
          >
            {{ showEditAnnouncementModal && currentAnnouncement.status === 'draft' ? '保存草稿' : '保存' }}
          </button>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
export default {
  name: 'AnnouncementManage',
  data() {
    return {
      showAddAnnouncementModal: false,
      showEditAnnouncementModal: false,
      searchKeyword: '',
      selectedStatus: '',
      currentAnnouncement: {
        id: null,
        title: '',
        content: '',
        status: 'draft', // draft, published, expired
        isTop: false,
        createTime: null,
        publishTime: null,
        expireTime: null,
        viewCount: 0
      },
      announcements: [
        {
          id: 1,
          title: '系统维护通知',
          content: '尊敬的用户，为了提供更好的服务，我们将于本周五晚23:00至周六凌晨3:00进行系统维护。维护期间可能无法正常使用系统功能，请您提前做好准备。给您带来的不便，敬请谅解！',
          status: 'published',
          isTop: true,
          createTime: '2023-07-10T09:30:00',
          publishTime: '2023-07-10T10:00:00',
          expireTime: '2023-07-15T23:59:59',
          viewCount: 256
        },
        {
          id: 2,
          title: '新功能上线公告',
          content: '我们很高兴地宣布，工单系统已完成新一轮升级，新增了以下功能：1. 工单批量处理功能；2. 自定义报表导出；3. 多语言支持。欢迎体验并提出宝贵意见！',
          status: 'published',
          isTop: false,
          createTime: '2023-07-05T14:20:00',
          publishTime: '2023-07-05T15:00:00',
          expireTime: null,
          viewCount: 189
        },
        {
          id: 3,
          title: '用户使用指南更新',
          content: '为帮助新用户快速上手，我们更新了系统使用指南，包含详细的操作步骤和常见问题解答。您可以在"帮助中心"查看完整指南。',
          status: 'draft',
          isTop: false,
          createTime: '2023-07-12T11:15:00',
          publishTime: null,
          expireTime: '2023-08-12T23:59:59',
          viewCount: 0
        },
        {
          id: 4,
          title: '五一假期服务调整',
          content: '五一假期期间（4月29日至5月3日），工单处理时效将延长至24小时内响应，5月4日起恢复正常服务。祝大家节日快乐！',
          status: 'expired',
          isTop: false,
          createTime: '2023-04-25T08:45:00',
          publishTime: '2023-04-25T09:00:00',
          expireTime: '2023-05-04T00:00:00',
          viewCount: 320
        }
      ]
    };
  },
  computed: {
    filteredAnnouncements() {
      return this.announcements.filter(announcement => {
        const matchesStatus = !this.selectedStatus || announcement.status === this.selectedStatus;
        const matchesSearch = !this.searchKeyword || 
          announcement.title.toLowerCase().includes(this.searchKeyword.toLowerCase()) ||
          announcement.content.toLowerCase().includes(this.searchKeyword.toLowerCase());
        return matchesStatus && matchesSearch;
      }).sort((a, b) => {
        // 排序：置顶的在前，然后按发布时间倒序
        if (a.isTop && !b.isTop) return -1;
        if (!a.isTop && b.isTop) return 1;
        
        const dateA = a.publishTime || a.createTime;
        const dateB = b.publishTime || b.createTime;
        return new Date(dateB) - new Date(dateA);
      });
    }
  },
  methods: {
    goToHome() {
      this.$router.push('/home');
    },
    formatDate(dateString) {
      if (!dateString) return '';
      const date = new Date(dateString);
      return date.toLocaleString('zh-CN', {
        year: 'numeric',
        month: '2-digit',
        day: '2-digit',
        hour: '2-digit',
        minute: '2-digit'
      });
    },
    filterAnnouncements() {
      // 过滤逻辑在计算属性中实现
    },
    editAnnouncement(announcement) {
      this.currentAnnouncement = JSON.parse(JSON.stringify(announcement));
      this.showEditAnnouncementModal = true;
    },
    deleteAnnouncement(id) {
      if (confirm('确定要删除这条公告吗？')) {
        this.announcements = this.announcements.filter(ann => ann.id !== id);
      }
    },
    publishAnnouncement(id) {
      const announcement = this.announcements.find(ann => ann.id === id);
      if (announcement) {
        announcement.status = 'published';
        announcement.publishTime = new Date().toISOString().slice(0, 16);
      }
    },
    toggleTop(id) {
      const announcement = this.announcements.find(ann => ann.id === id);
      if (announcement) {
        announcement.isTop = !announcement.isTop;
      }
    },
    expireAnnouncement(id) {
      const announcement = this.announcements.find(ann => ann.id === id);
      if (announcement && confirm('确定要将这条公告设为过期吗？')) {
        announcement.status = 'expired';
        announcement.expireTime = new Date().toISOString().slice(0, 16);
      }
    },
    closeAnnouncementModal() {
      this.showAddAnnouncementModal = false;
      this.showEditAnnouncementModal = false;
      this.resetCurrentAnnouncement();
    },
    resetCurrentAnnouncement() {
      this.currentAnnouncement = {
        id: null,
        title: '',
        content: '',
        status: 'draft',
        isTop: false,
        createTime: new Date().toISOString().slice(0, 16),
        publishTime: null,
        expireTime: null,
        viewCount: 0
      };
    },
    saveAnnouncement() {
      // 简单验证
      if (!this.currentAnnouncement.title.trim()) {
        alert('请输入公告标题');
        return;
      }
      
      if (!this.currentAnnouncement.content.trim()) {
        alert('请输入公告内容');
        return;
      }
      
      if (this.showEditAnnouncementModal) {
        // 更新现有公告
        const index = this.announcements.findIndex(ann => ann.id === this.currentAnnouncement.id);
        if (index !== -1) {
          this.announcements.splice(index, 1, JSON.parse(JSON.stringify(this.currentAnnouncement)));
        }
      } else {
        // 添加新公告
        this.currentAnnouncement.id = Date.now();
        this.currentAnnouncement.createTime = new Date().toISOString().slice(0, 16);
        this.announcements.push(JSON.parse(JSON.stringify(this.currentAnnouncement)));
      }
      
      this.closeAnnouncementModal();
    },
    saveAndPublish() {
      this.currentAnnouncement.status = 'published';
      this.currentAnnouncement.publishTime = new Date().toISOString().slice(0, 16);
      this.saveAnnouncement();
    }
  }
}
</script>

<style scoped>
.announcement-page {
  padding: 20px;
  background-color: #f5f7fa;
  min-height: 100vh;
}

.page-header {
  display: flex;
  align-items: center;
  margin-bottom: 20px;
  padding-bottom: 15px;
  border-bottom: 1px solid #e1e5e8;
}

.back-button {
  display: flex;
  align-items: center;
  gap: 8px;
  padding: 10px 15px;
  background: #3498db;
  color: white;
  border: none;
  border-radius: 5px;
  cursor: pointer;
  transition: all 0.3s;
  margin-right: 20px;
  font-weight: 500;
}

.back-button:hover {
  background: #2980b9;
  transform: translateY(-2px);
}

.page-content {
  margin-top: 20px;
}

.config-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.config-header p {
  color: #666;
  font-size: 14px;
}

.card {
  background: white;
  border-radius: 10px;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.05);
  padding: 20px;
}

.filter-bar {
  display: flex;
  gap: 10px;
  margin-bottom: 20px;
  flex-wrap: wrap;
}

.filter-select {
  padding: 10px 15px;
  border: 1px solid #ddd;
  border-radius: 5px;
  font-size: 14px;
  background-color: white;
}

.search-input {
  flex: 1;
  min-width: 200px;
  padding: 10px 15px;
  border: 1px solid #ddd;
  border-radius: 5px;
  font-size: 14px;
}

.search-btn {
  padding: 10px 20px;
  background: #f5f7fa;
  border: 1px solid #ddd;
  border-radius: 5px;
  cursor: pointer;
  transition: all 0.2s;
}

.search-btn:hover {
  background: #e9ecef;
}

.announcements-list {
  display: flex;
  flex-direction: column;
  gap: 15px;
}

.announcement-item {
  border: 1px solid #f0f0f0;
  border-radius: 8px;
  overflow: hidden;
  transition: all 0.2s;
}

.announcement-item:hover {
  box-shadow: 0 3px 15px rgba(0, 0, 0, 0.07);
}

.announcement-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 12px 15px;
  background-color: #f9fafb;
  border-bottom: 1px solid #f0f0f0;
}

.announcement-status {
  display: flex;
  gap: 8px;
  align-items: center;
}

.status-tag {
  padding: 3px 8px;
  border-radius: 4px;
  font-size: 12px;
  font-weight: 500;
}

.status-published {
  background-color: #e8f5e9;
  color: #388e3c;
}

.status-draft {
  background-color: #fff8e1;
  color: #f57c00;
}

.status-expired {
  background-color: #f5f5f5;
  color: #757575;
}

.top-tag {
  padding: 2px 6px;
  background-color: #ffebee;
  color: #d32f2f;
  border-radius: 3px;
  font-size: 11px;
  font-weight: 500;
}

.announcement-date {
  font-size: 12px;
  color: #666;
}

.announcement-body {
  padding: 15px;
}

.announcement-title {
  margin: 0 0 10px 0;
  font-size: 16px;
  color: #333;
}

.announcement-content {
  margin: 0 0 15px 0;
  font-size: 14px;
  color: #555;
  line-height: 1.6;
  word-break: break-word;
}

.announcement-meta {
  display: flex;
  gap: 15px;
  font-size: 12px;
  color: #777;
  padding-top: 10px;
  border-top: 1px dashed #eee;
}

.meta-item {
  display: flex;
  align-items: center;
  gap: 5px;
}

.icon-view::before {
  content: "👁️";
}

.icon-expire::before {
  content: "⏰";
}

.announcement-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
  padding: 10px 15px;
  background-color: #f9fafb;
  border-top: 1px solid #f0f0f0;
  flex-wrap: wrap;
}

.edit-btn, .delete-btn, .publish-btn, .top-btn, .expire-btn {
  padding: 6px 12px;
  border-radius: 4px;
  cursor: pointer;
  font-size: 13px;
  transition: all 0.2s;
  border: none;
}

.edit-btn {
  background-color: #e3f2fd;
  color: #1976d2;
}

.edit-btn:hover {
  background-color: #bbdefb;
}

.delete-btn {
  background-color: #ffebee;
  color: #d32f2f;
}

.delete-btn:hover {
  background-color: #ffcdd2;
}

.publish-btn {
  background-color: #e8f5e9;
  color: #388e3c;
}

.publish-btn:hover {
  background-color: #c8e6c9;
}

.top-btn {
  background-color: #fff3e0;
  color: #e65100;
}

.top-btn:hover {
  background-color: #ffe0b2;
}

.expire-btn {
  background-color: #f5f5f5;
  color: #757575;
}

.expire-btn:hover {
  background-color: #e0e0e0;
}

.empty-state {
  text-align: center;
  padding: 60px 0;
  color: #999;
}

.icon-empty::before {
  content: "📢";
  font-size: 48px;
  display: block;
  margin-bottom: 15px;
}

.primary-btn {
  display: inline-flex;
  align-items: center;
  gap: 5px;
  padding: 10px 15px;
  background: #3498db;
  color: white;
  border: none;
  border-radius: 5px;
  cursor: pointer;
  transition: all 0.3s;
  font-weight: 500;
}

.primary-btn:hover {
  background: #2980b9;
}

.icon-plus::before {
  content: "+";
}

.modal-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 1000;
}

.modal {
  background-color: white;
  border-radius: 10px;
  width: 700px;
  max-width: 90%;
  max-height: 80vh;
  overflow-y: auto;
  box-shadow: 0 5px 15px rgba(0, 0, 0, 0.2);
}

.modal-header {
  padding: 15px 20px;
  border-bottom: 1px solid #eee;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.modal-header h3 {
  margin: 0;
  font-size: 18px;
}

.close-btn {
  background: none;
  border: none;
  font-size: 20px;
  cursor: pointer;
  color: #999;
}

.modal-body {
  padding: 20px;
}

.announcement-form {
  display: flex;
  flex-direction: column;
  gap: 15px;
}

.form-group {
  display: flex;
  flex-direction: column;
  gap: 5px;
}

.form-group label {
  font-weight: 500;
  font-size: 14px;
}

.form-control {
  padding: 10px;
  border: 1px solid #ddd;
  border-radius: 5px;
  font-size: 14px;
}

.announcement-content {
  font-family: inherit;
  resize: vertical;
}

.form-hint {
  margin: 5px 0 0 0;
  font-size: 12px;
  color: #777;
  margin-top: 3px;
}

.checkbox-label {
  display: flex;
  align-items: center;
  gap: 8px;
  cursor: pointer;
}

.form-actions {
  display: flex;
  justify-content: flex-start;
  margin-top: 5px;
}

.modal-publish-btn {
  padding: 8px 15px;
}

.modal-footer {
  padding: 15px 20px;
  border-top: 1px solid #eee;
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}

.cancel-btn {
  padding: 8px 15px;
  background: #f5f5f5;
  border: 1px solid #ddd;
  border-radius: 5px;
  cursor: pointer;
  transition: all 0.2s;
}

.cancel-btn:hover {
  background: #e9e9e9;
}

.icon-arrow-left::before {
  content: "←";
}
</style>